CalendarService    = Packages.com.google.gdata.client.calendar.CalendarService;
gdata              = Packages.com.google.gdata.data;
AclEntry           = Packages.com.google.gdata.data.acl.AclEntry;
AclScope           = Packages.com.google.gdata.data.acl.AclScope;
CalendarAclRole    = Packages.com.google.gdata.data.calendar.CalendarAclRole;
CalendarEventEntry = Packages.com.google.gdata.data.calendar.CalendarEventEntry;
DateTime           = Packages.com.google.gdata.data.DateTime;
When               = Packages.com.google.gdata.data.extensions.When;
PlainTextConstruct = Packages.com.google.gdata.data.PlainTextConstruct;
EventWho           = Packages.com.google.gdata.data.calendar.EventWho;
Query              = Packages.com.google.gdata.client.Query
CalendarEventFeed  = Packages.com.google.gdata.data.calendar.CalendarEventFeed
Reminder           = Packages.com.google.gdata.data.extensions.Reminder
Method             = Packages.com.google.gdata.data.extensions.Reminder.Method;
Where              = Packages.com.google.gdata.data.extensions.Where;
ExtendedProperty   = Packages.com.google.gdata.data.extensions.ExtendedProperty;
SimpleDateFormat   = Packages.java.text.SimpleDateFormat;
ParseException     = Packages.java.text.ParseException;
Date               = Packages.java.util.Date;
CalendarEventFeed  = Packages.com.google.gdata.data.calendar.CalendarEventFeed;
Link               = Packages.com.google.gdata.data.Link;
BatchUtils         = Packages.com.google.gdata.data.batch.BatchUtils;
BatchOperationType = Packages.com.google.gdata.data.batch.BatchOperationType;

function main( ui ) {
   //.getQueryParameters()
  var json = ui.getFirst("json");
    if ( json == null ){
        var ex = "{ exception: { message: 'no param provided'} }";
        return ex;
  }
    var o = new JSONObject( json );
    var appointments= o.getJSONArray("records");
    var service = new CalendarService("demo-calendar-1");
    var postUrl = null;   
    var myEntry = null;   
    var username = "soulsoftware2010@gmail.com";
    var password = "2010soulsoftware";
    service.setUserCredentials(username, password);
  
    var o;
    var titleAppointment;
    var contentAppointment;
    var emailEmployee;
    var startAppointment;
    var endAppointment;
    var idCalendar;
    var address;  
  
    var i=0;
    for (;i<appointments.length();i++){
      try {
           o=appointments.getJSONObject(i);
           titleAppointment=o.get("TITLE");
           contentAppointment=o.get("description");
           emailEmployee=o.get("userId");
           startAppointment=o.get("STARTDATE");
           endAppointment=o.get("ENDDATE");
           idCalendar=o.get("IDCALENDAR");
           address=o.get("address");
           
           var timeStartOffsetAppointment=o.get("TIMEZONE_START_TIMEOFFSETAPPOINTMENT_JSON_KEY");
           var timeStartOffsetEmployee=o.get("TIMEZONE_START_TIMEOFFSETEMPLOYEE_JSON_KEY");
           var timeEndOffsetAppointment=o.get("TIMEZONE_END_TIMEOFFSETAPPOINTMENT_JSON_KEY");
           var timeEndOffsetEmployee=o.get("TIMEZONE_END_TIMEOFFSETEMPLOYEE_JSON_KEY");
           var tzEmployee=o.get("TIMEZONE_EMPLOYEE_JSON_KEY");
           var tzAppointment=o.get("TIMEZONE_APPOINTMENT_JSON_KEY");

           var cal1 = java.util.Calendar.getInstance();
           
           cal1.setTimeInMillis(o.get("from"));
           var startDate = cal1.getTime();
           o.put("from",startDate);
      
           cal1.setTimeInMillis(o.get("to"));
           var endDate = cal1.getTime();
           o.put("to",endDate);
           
           var event = new EventEntity();
              
           o.copyTo( event );
           
           cal1 = java.util.Calendar.getInstance();
           cal1.setTimeInMillis(o.get("from2"));
           startDate = cal1.getTime();
           cal1.setTimeInMillis(o.get("to2"));
           endDate = cal1.getTime();
        
           BOLEntityManager.createEvent( event );
      
           var jsonUID = new JSONObject(event);
           
           var idEventCloud=jsonUID.get("UID");
          
           //ADD APPOINTMENT GOOGLE CALENDAR
           postUrl =
           new java.net.URL("https://www.google.com/calendar/feeds/"+idCalendar+"/private/full");
           
           myEntry = new CalendarEventEntry();
      
           contentAppointment=contentAppointment + " (EMPLOYEE GMT :" + (timeStartOffsetEmployee/60) + " " + tzEmployee +
            " - APPOINTMENT GMT :" +(timeStartOffsetAppointment/60)+ " " + tzAppointment +")";
             
           myEntry.setTitle(new PlainTextConstruct(titleAppointment));
           myEntry.setContent(new PlainTextConstruct(contentAppointment));
           var eventWho=new EventWho();
           eventWho.setEmail(emailEmployee);
           myEntry.addParticipant(eventWho);
        
           var calendar = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone(tzAppointment));
           var formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
           var dateStart = formatter.parse(startAppointment);  
           var dateEnd = formatter.parse(endAppointment) ;

           calendar.setTime(startDate);
           var calculate=((-1)*timeStartOffsetEmployee *60*1000)-((-1)*timeStartOffsetAppointment*60*1000);
           var timeStartEmployee = new java.util.GregorianCalendar(java.util.TimeZone.getTimeZone(tzEmployee));
           timeStartEmployee.setTimeInMillis(calendar.getTimeInMillis() + calculate);
      
           calendar.setTime(endDate);
           calculate=((-1)*timeEndOffsetEmployee *60*1000)-((-1)*timeEndOffsetAppointment*60*1000);
           var timeEndEmployee = new java.util.GregorianCalendar(java.util.TimeZone.getTimeZone(tzEmployee));
           timeEndEmployee.setTimeInMillis(calendar.getTimeInMillis() + calculate);
          
      
           var startTime = new DateTime(timeStartEmployee.getTime(),java.util.TimeZone.getTimeZone(tzEmployee));
           var endTime = new DateTime(timeEndEmployee.getTime(),java.util.TimeZone.getTimeZone(tzEmployee));
           
           
      
           var eventTimes = new When();
           eventTimes.setStartTime(startTime);
           eventTimes.setEndTime(endTime);
           myEntry.addTime(eventTimes);
           var where=new Where();
           where.setValueString(address);
           myEntry.addLocation(where);
      
           //EXTENDEDPROPERTY
           var property = new ExtendedProperty();
           property.setName("IDEVENT_KEYEXT");
           property.setValue(idEventCloud);
           myEntry.addExtendedProperty(property);
      
           //ADD REMIND
           var reminder = new Reminder();
           reminder.setMinutes(10);
           reminder.setMethod(Method.EMAIL);
           myEntry.getReminder().add(reminder);
      
           service.insert(postUrl, myEntry);
          
        }catch( e ) {
          //ROLLBACK APPOINTMENT CALENDAR
          var batchRequest = new CalendarEventFeed();
          BatchUtils.setBatchId(myEntry, String.valueOf("1"));
          BatchUtils.setBatchOperationType(myEntry, BatchOperationType.DELETE);
          batchRequest.getEntries().add(myEntry);
          var feed = service.getFeed(postUrl,CalendarEventFeed);
          var batchLink = feed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM);
          var batchUrl = new java.net.URL(batchLink.getHref());
          service.batch(batchUrl, batchRequest);
          
          var message ="Exception : " +titleAppointment;
          message=message + " Employee: " + emailEmployee;
          message=message + " Start date" + startAppointment;
          message=message + " End date" + endAppointment;
          throw message;
          //throw new java.lang.Exception(message);
      }
     }
  return "{result:'OK'}";
}

